package com.tangtang.mvc.controller;

import com.tangtang.core.basic.PagedQuery;
import com.tangtang.core.tree.Tree;
import com.tangtang.security.model.SysResource;
import com.tangtang.security.service.UserService;
import com.tangtang.security.view.model.SysViewResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping(value = "/resource")
public class ResourceController extends BaseController {
    @Autowired
    UserService userService;


    String editView = "resource/add";

    @RequestMapping(value = "/list.do")
    public ModelAndView index(Integer pageIndex) {
        final String rurl = super.request.getServletPath();
        PagedQuery<SysResource> page = userService.getResource(pageIndex, 1000);
        ModelAndView mav = new ModelAndView("resource/list");
        mav.addObject("requesturl", rurl);
        mav.addObject("page", page);
        return mav;
    }

    @RequestMapping(value = "/add.do", method = RequestMethod.GET)
    public ModelAndView add(Integer id) throws IOException {
        response.getWriter().append(request.getServletPath());
        SysResource resource = new SysResource();
        if (id != null && id > 0) {
            resource = userService.getResource(id);
            if (resource == null) {
                return view(editView, false, "资源参数错误");
            }
        }
        return view(editView, resource);
    }

    /**
     * 保存resource
     *
     * @param record sys_resource model
     * @return modelAndView
     */
    @RequestMapping(value = "/add.do", method = RequestMethod.POST)
    public ModelAndView add(@Valid SysResource record, BindingResult result) {
        if (result.hasErrors()) {
            return view(editView, false);
        }
        Boolean success;
        if (record != null && record.getResourceId() != null && record.getResourceId() > 0) {
            success = userService.updateResource(record);
            return view(editView, success, success ? "编辑成功" : "编辑失败");
        } else {
            success = userService.insertResource(record);
            return view(editView, success, success ? "添加成功" : "添加失败");
        }
    }

    /**
     * @param resourceParentId parentId
     * @return
     */
    @RequestMapping(value = "/gettree.do", method = RequestMethod.GET)
    public ModelAndView getTree(Integer resourceParentId) {
        List<Tree<SysViewResource>> tree = userService.getMenusTreeByUserId(0);
        ModelAndView mav = new ModelAndView("resource/gettree");
        mav.addObject("tree", tree);
        return mav;
    }
}
